<template>
  <div>
    <div class="logo-page" v-if="isVisible">
      <div class="nav">
        <img src="./../assets/img/login/logo.png" alt="" />
        河北省流域地表水管控平台
      </div>
      <div class="content">
        <img class="bg_img" src="./../assets/img/login/bg.png" alt="">
        <div class="log-on">
          <div class="form-login">
            <div style="text-align: center;margin-bottom: 20px;">
              <span style="color: #39f;font-size: 20px;">用户登录</span>
            </div>
            <div class="login-content">
              <div class="logoCon">
                <div class="logNr">
                  <el-input class="myinput" type="text" v-model="ruleForm.username" auto-complete="off"
                    placeholder="请输入您的用户名" @keyup.enter.native="submitForm()" />
                  <i class="ic user"></i>
                </div>
                <div class="logNr">
                  <el-input class="myinput" type="password" v-model="ruleForm.password" auto-complete="off"
                    placeholder="请输入您的密码" show-password @keyup.enter.native="submitForm()"></el-input>
                  <i class="ic pass"></i>
                </div>
                <div class="logNr">
                  <el-input class="myinput yzmInput" type="text" v-model="ruleForm.code" auto-complete="off"
                    placeholder="验证码" @keyup.enter.native="submitForm()"></el-input>
                  <i class="ic yzmi"></i>
                  <img :src="ruleForm.codeimg" alt="" class="yzmPic" @click="getcode()" />
                </div>
                <el-button class="btnWz" type="primary" style="width: 100%" @click="submitForm()">登录</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footer"></div>
    </div>
    <div v-else v-loading="isLoading"></div>
  </div>
</template>
<script>
import VueRouter from 'vue-router';
import router, { routes } from "@/router/index";
import { getRouter } from "@/router/router.js";
import axios from "axios";
import store from "../store";
export default {
  data() {
    return {
      ruleForm: {
        //username和password默认为空
        username: "admin",
        password: "admin!QAZ2wsx#EDC123",
        code: "",
        codeimg: "",
      },
      isVisible: false,
      uuid: null,
    };
  },
  mounted() {
   //跳转过来，带token
    if (this.idLogedin()) {
      this.isVisible = false
      this.$router.push({
        path: "/",
      });
      this.isLoading = false
    } else {
      this.isVisible = true
      this.getcode();   // 获取图形验证码
    }
  },
  methods: {
    idLogedin() {
      const urlParams = new URLSearchParams(window.location.search);
      const tokenFromUrl = urlParams.get('token') || '';
      const userName = urlParams.get('userName') || '';
      if (tokenFromUrl) {
        // 如果 token 存在，执行登录操作
        const decodedToken = this.parseJwt(tokenFromUrl); // 假设 parseJwt 是解码 JWT 的函数
        if(userName){
          decodedToken.realName = userName;
          decodedToken.nickName = userName;
        }
        decodedToken.access_token = tokenFromUrl
        localStorage.setItem('loginTime', new Date().getTime()); // 记录登录时间
        localStorage.setItem('authToken', tokenFromUrl); // 存储 token
        localStorage.setItem('userInfo', JSON.stringify(decodedToken)); // 存储用户信息
        return this.getRourter()
        //this.getTreeData()
      }
      return false
    },
    parseJwt(token) {
      const parts = token.split('.');
      let payload = JSON.parse(atob(parts[1]));
      return payload;
    },
    getcode() {
      this.uuid = new Date().getTime();
      let img = this.$api.getImgVerification(this.uuid);
      this.ruleForm.codeimg = img;
    },
    //获取info列表
    submitForm() {
      let params = {
        username: this.ruleForm.username,
        password: this.ruleForm.password,
        code: this.ruleForm.code,
        uuid: this.uuid,
        grant_type: "password",
      };
      this.$api.oauthToken(params).then((res) => {
        if (res && res.code == 200) {
          let data = res.data || {};
          localStorage.setItem("loginTime", new Date().getTime());
          localStorage.setItem("authToken", data.access_token);
          localStorage.setItem("userInfo", JSON.stringify(data));
          return this.getRourter()
        } else {
          this.getcode();
          return false;
        }
      });
    },
    // 获取路由
    getRourter() {
      this.$api.getMenuManageList({ orderBy: "sort" }).then((res) => {
        if (res && res.code === 200) {
          let data = res.data;
          localStorage.setItem('menuList', JSON.stringify(data))
          const newRoutes = routes;
          Promise.all([getRouter(data, newRoutes)]).then((result) => {
            console.log(result[0]);
            const newRouter = new VueRouter({
              mode: "hash",
              routes: result[0],
            });
            router.matcher = newRouter.matcher;
            var token = window.encodeURI(localStorage.getItem("authToken"));
            var userInfo = JSON.parse(localStorage.getItem("userInfo"));
            var realName = window.encodeURI(userInfo.realName);
            var userName = userInfo.account;
            this.$router.push({
              path: "/",
            });
          });
          this.getTreeData()
          // 清除 URL 中的 token 参数
          const newUrl = window.location.origin + window.location.pathname; // 获取没有参数的 URL
          window.history.replaceState({}, document.title, newUrl); // 修改浏览器地址栏
          return true
        }else{
          this.$store.commit("logout", "false");
          this.$router.push({path: '/login'})
          this.$router.push({
            name: "reload-page",
            params: { name: "login" },
          });
          localStorage.setItem('authToken', '')
          localStorage.setItem('userInfo', '')
          return false
        }
      });
    },
    getTreeData() {
      this.$api.getAreaTree({}).then((res) => {
        if (res && res.code == 200) {
          const areaTree = res.data || []
          this.$store.commit("set_areaTree", areaTree);
        }
      })

      this.$api.getBasinTree({}).then((res) => {
        if (res && res.code == 200) {
          const basinOptions = res.data || []
          this.$store.commit("set_basinOptions", basinOptions);
        }
      })
    }
  },
};
</script>
<style lang="less" scoped>
.logo-page {
  background-color: #fff;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .nav {
    flex: 1;
    display: flex;
    align-items: center;
    letter-spacing: 2px;
    color: #0f7de2;
    font-size: 28px;

    img {
      padding-left: 50px;
      padding-right: 10px;
    }
  }

  .content {
    position: relative;

    .bg_img {
      width: 100%;
    }

    .log-on {
      border-radius: 10px;
      background-color: #fff;
      overflow: hidden;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 20%;

      img {
        width: 360px;
      }

      .form-login {
        background: #fff;
        width: 350px;
        float: right;
        box-sizing: border-box;
        padding: 40px;

        .login-content {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          .logoPic {
            cursor: pointer;
          }

          .logoCon {
            width: 100%;
            box-sizing: border-box;
            border-radius: 10px;
            margin-top: 25px;
            text-align: center;
            z-index: 10;

            .dlwz {
              margin: 0 0 20px 0;
            }

            .logNr {
              border-bottom: 0px #1f8cca solid;
              height: 40px;
              margin: 0 0 20px 0;
              clear: both;
              position: relative;

              .ic {
                position: absolute;
                width: 16px;
                height: 16px;
                display: block;
                left: 15px;
                top: 13px;

                &.user {
                  background: url("./../assets/img/login/people.png") center no-repeat;
                  background-size: 100%;
                }

                &.pass {
                  background: url("./../assets/img/login/lock.png") center no-repeat;
                  background-size: 90%;
                }

                &.yzmi {
                  background: url("./../assets/img/login/key.png") center no-repeat;
                  background-size: 100%;
                }
              }

              .myinput {
                height: 42px;
                width: 100%;
                border-radius: 5px;
                border: 1px #dbe6f6 solid;
                background: #fff;
                font-size: 16px;
                line-height: 40px;
                color: #777777;
                box-sizing: border-box;
                padding: 0 0 0 30px;
                overflow: hidden;


                &:hover {
                  color: #000;
                }

                &.yzmInput {
                  float: left;
                  width: 150px;
                }
              }

              .yzmPic {
                width: 110px;
                height: 42px;
                float: right;
                cursor: pointer;
              }
            }

            .btnWz {
              display: block;
              clear: both;
              height: 42px;
              // border-radius: 21px;
              font-size: 15px;
              font-weight: 500;
              color: #fff;
              text-align: center;
              cursor: pointer;
              margin-top: 30px;
              // background: linear-gradient(180deg, #579AFF 0%, #3066BE 100%);
              // box-shadow: inset 0px -4px 4px rgba(0, 0, 0, 0.25), inset 0px 4px 4px rgba(249, 247, 243, 0.25);


              &:hover {
                opacity: .9;
              }
            }

            .user-pass {
              font-size: 14px;
              margin-top: 25px;
            }
          }
        }
      }
    }
  }

  .footer {
    flex: 1;
  }
}
</style>
<style lang="less">
.logo-page {
  .el-input .el-input__inner {
    background: transparent;
    border: none;

    &::-webkit-input-placeholder {
      color: #d5d5d6;
    }
  }
}
</style>
